"""
-*- coding: utf-8 -*-
@Time    : 2025/7/7 18:40
@Author  : issca_new
@File    : 贪吃蛇.py
@Software: PyCharm
@Attention:美色迷人心智，伤人根骨,瓦解人的意志
"""

import pygame,sys,random
from pygame.locals import *

#初始化颜色
RED = pygame.Color(255,0,0)
#目标方块的颜色
WHITE = pygame.Color(255,255,255)
#贪吃蛇的颜色
BLACK = pygame.Color(0,0,0)
#背景颜色

def GAMEOVER(): #游戏结束
    # 游戏结束
    pygame.quit()
    #pygame 退出
    sys.exit()
    #系统退出

global CHANG,KUAN,JIBEN,SNACKPOSITION,TARGET_POSITION
JIBEN = 50
CHANG = JIBEN*20
KUAN = JIBEN*15

SNACKPOSITION = [JIBEN*5, JIBEN*5]
TARGET_POSITION = [JIBEN*7, JIBEN*7]

def target_not_in_snack():
    global TARGET_POSITION
    if TARGET_POSITION in SNACKPOSITION:
        x = random.randrange(1, (CHANG / JIBEN) - 1)
        y = random.randrange(1, (KUAN / JIBEN) - 1)
        TARGET_POSITION = [int(x * JIBEN), int(y * JIBEN)]
        target_not_in_snack()

def main():
    global FPS
    global PLAYSURFACE
    pygame.init()
    FPS = pygame.time.Clock()
    PLAYSURFACE = pygame.display.set_mode((CHANG, KUAN))
    pygame.display.set_caption('蛇')
    while True:
        """
        游戏背景音乐
        """
        # if random.randint(0, 1) == 0:
        #     try:
        #         pygame.mixer.music.load('鸡你太美.mp3')
        #     except:
        #         pass
        # else:
        #     pass
        # pygame.mixer.music.play(-1, 0.0)
        Rungame()
        # pygame.mixer.music.stop()


def Rungame():
    global SNACKPOSITION,TARGET_POSITION
    pygame.init()#初始化pygame


    """
    加载图片，是重点
    由于打包成exe后，os无法读取exe所在文件（可能是我菜），所以偷懒
    将50×50像素的若干png格式的照片（也可以jpg，注意改代码），放在exe或py文件同文件夹下，命名为face1.png、face2.png、face3.png、
    face4.png、face5.png.........
    然后运行即可
    
    """
    name_list = ["face"+str(i)+".png" for i in range(1,100)]

    #allim = [pygame.image.load(os.path.join(m_path,name)) for name in os.listdir(m_path) if os.path.splitext(name)[1].lower()==".png"]
    allim = []
    for i in range(0,len(name_list)):
        try:
            allim.append(pygame.image.load(name_list[i]))
        except:
            pass



    SNACK_imrange = [allim[random.randrange(0,len(allim))],allim[random.randrange(0,len(allim))],allim[random.randrange(0,len(allim))]]
    tao = random.randrange(0, len(allim))

    #
    FPS = pygame.time.Clock()#定义一个变量来控制游戏速度


    PLAYSURFACE = pygame.display.set_mode((CHANG,KUAN))#创建pygame显示层

    pygame.display.set_caption('xxx')#设置标题


    SNACK_BODY = [[JIBEN*5, JIBEN*5], [JIBEN*4, JIBEN*5], [JIBEN*3, JIBEN*5]]
    SNACK_LEN = len(SNACK_BODY)

    TARGET_FLAG = 1

    DIRECTION = 'right'
    CHANGE_DIRECTION = DIRECTION

    while True :
        for event in pygame.event.get():#获得游戏事件
            if event.type == QUIT:
                GAMEOVER()
            elif event.type == KEYDOWN:
                if event.key == K_RIGHT:
                    CHANGE_DIRECTION = 'right'
                if event.key == K_LEFT:
                    CHANGE_DIRECTION = 'left'
                if event.key == K_UP:
                    CHANGE_DIRECTION = 'up'
                if event.key == K_DOWN:
                    CHANGE_DIRECTION = 'down'
                if event.key == K_ESCAPE:
                    pygame.event.post(pygame.event.Event(QUIT))
                # 蛇的转向
        if CHANGE_DIRECTION == 'left' and not DIRECTION == 'right':
            DIRECTION = CHANGE_DIRECTION

        if CHANGE_DIRECTION == 'right' and not DIRECTION == 'left':
            DIRECTION = CHANGE_DIRECTION

        if CHANGE_DIRECTION == 'up' and not DIRECTION == 'down':
            DIRECTION = CHANGE_DIRECTION

        if CHANGE_DIRECTION == 'down' and not DIRECTION == 'up':
            DIRECTION = CHANGE_DIRECTION
        #根据方向移动蛇头
        if DIRECTION == 'right':
            SNACKPOSITION[0] += JIBEN
        if DIRECTION == 'left':
            SNACKPOSITION[0] -= JIBEN
        if DIRECTION == 'up':
            SNACKPOSITION[1] -= JIBEN
        if DIRECTION == 'down' :
            SNACKPOSITION[1] += JIBEN
        #增加蛇的长度

        SNACK_BODY.insert(0, list(SNACKPOSITION))


        if SNACKPOSITION[0] == TARGET_POSITION[0] and SNACKPOSITION[1] == TARGET_POSITION[1] :#判断蛇头位置是否与食物位置相同
            TARGET_FLAG = 0
            SNACK_LEN += 1
            SNACK_imrange.insert(0,allim[tao])
        else :
            SNACK_BODY.pop()

        if TARGET_FLAG == 0:#当食物被吃掉时
            x = random.randrange(1,(CHANG/JIBEN)-1)
            y = random.randrange(1,(KUAN/JIBEN)-1)
            TARGET_POSITION = [int(x*JIBEN),int(y*JIBEN)]
            target_not_in_snack()

            TARGET_FLAG = 1
            tao=random.randrange(0,len(allim))
        pygame.display.flip()
        # 判断是否死亡
        if SNACKPOSITION[0] > (CHANG-JIBEN) or SNACKPOSITION[0] < 0:
            GAMEOVER()

        elif SNACKPOSITION[1] > (KUAN-JIBEN) or SNACKPOSITION[1] < 0:
            GAMEOVER()
        if SNACK_LEN > 4:
            if SNACKPOSITION in SNACK_BODY[1:SNACK_LEN]:
                GAMEOVER()
        #绘制pygame显示层
        PLAYSURFACE.fill(BLACK)
        PLAYSURFACE.blit(allim[tao], (TARGET_POSITION[0], TARGET_POSITION[1]))

        for i in range(0, SNACK_LEN):
            PLAYSURFACE.blit(SNACK_imrange[i], (SNACK_BODY[i][0], SNACK_BODY[i][1]))

        FPS.tick(5)
if __name__ == '__main__':
       main()














